<?php
namespace mybackend\controllers;

use Yii;
use common\services\myhtsq\InvoiceService;
use common\models\myhtsq\InvoiceModel;
use common\error\ErrorCode;
use common\entities\myhtsq\ActionCode;
use yii\filters\AccessControl;

/**
 * Description of InvoiceController
 * 发票控制器
 * @author chenxc
 */
class InvoiceController extends BaseController {

    private $_invoiceService;

    public function __construct($id, $module, InvoiceService $invoiceService, $config = array()) {
        $this->_invoiceService = $invoiceService;
        parent::__construct($id, $module, $config);
    }

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['invoice-expired-remind'],
                        'allow' => true,
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    protected function roleAuthRules(){
        return [
            'actions'=>['DeleteInvoice','DoLose','GetInvoiceInfo','GetInvoiceListByPage','SaveInvoice','ExportInvoice', 'ExportUnInvoicePayment'],
            'rules'=>[
                        [
                        'allow'=>true,
                        'actionCodeMaps'=>[
                            'DeleteInvoice'=>ActionCode::INVOICE_MNG,
                            'DoLose'=>ActionCode::INVOICE_MNG,
                            'GetInvoiceInfo'=>ActionCode::INVOICE_VIEW,
                            'GetInvoiceListByPage'=>ActionCode::INVOICE_VIEW,
                            'SaveInvoice'=>ActionCode::INVOICE_MNG,
                            'ExportUnInvoicePayment' => ActionCode::FP_EXPORT,
                             'ExportInvoice' =>ActionCode::FP_EXPORT,
                            ]
                        ]
                    ]
                ];
    }

    /**
     * 发票管理模块：获取发票列表信息，支持分页
     */
    public function actionGetInvoiceListByPage() {
        $invoiceModel = new InvoiceModel(['scenario' => 'getinvoicelistbypage']);
        if ($invoiceModel->paramsGetValidate()) {
            $params = $invoiceModel->getAttributes();

            $invoice_mix_receipt = $this->getParam("invoice_mix_receipt");
            $data = $this->_invoiceService->getInvoiceListByPage($params['is_main_invoice'], $params['invoice_status'], $params['invoice_begin_date'], $params['invoice_end_date'], $params['searchKey'], $params['pageIndex'], $params['pageSize'],$invoice_mix_receipt);

            return $this->json([
                        'retCode' => ErrorCode::SUCCESS,
                        'data' => $data
            ]);
        } else {
            Yii::error($invoiceModel->getLogMsg());
            return $this->json([
                        'retCode' => $invoiceModel->getErrCode(),
                        'errMsg' => $invoiceModel->getErrMsg(),
            ]);
        }
    }

    /**
     * 获取单个发票信息
     */
    public function actionGetInvoiceInfo() {
        $invoiceId = $this->getParam("invoiceId");
        $result = $this->_invoiceService->getInvoiceInfo($invoiceId);
        $this->exportJson($result, $this->_invoiceService->getErrCode(), $this->_invoiceService->getErrMsg());
    }

    /**
     * 保存发票
     */
    public function actionSaveInvoice() {
        $this->exitIfNotPost();
        $invoiceModel = new InvoiceModel(['scenario' => 'saveinvoice']);
        $invoiceModel->is_import = 0;
        if ($invoiceModel->load(Yii::$app->request->post(), '')) {
            $result = $this->_invoiceService->saveInvoice($invoiceModel);
            $this->exportJson($result, $this->_invoiceService->getErrCode(), $this->_invoiceService->getErrMsg());
        } else {
            $this->errorParam();
        }
    }

    /**
     * 删除发票
     */
    public function actionDeleteInvoice() {
        $invoiceId = $this->getParam("invoiceId");
        $result = $this->_invoiceService->deleteInvoice($invoiceId);
        $this->exportJson($result, $this->_invoiceService->getErrCode(), $this->_invoiceService->getErrMsg());
    }

    /**
     * 标记遗失
     */
    public function actionDoLose() {
        $invoiceId = $this->getParam("invoiceId");
        $result = $this->_invoiceService->doLose($invoiceId);
        $this->exportJson($result, $this->_invoiceService->getErrCode(), $this->_invoiceService->getErrMsg());
    }
    
    /**
     * 获取发票列表（select2控件）
     * @param string $keyword 搜索关键字
     * @param string $page 分页
     */
    public function actionGetInvoiceListForSepcialInvoiceSelect2($keyword,$limit){
        $result = $this->_invoiceService->getInvoiceListForSepcialInvoiceSelect2($keyword,$limit);
        $this->exportJson($result, $this->_invoiceService->getErrCode(), $this->_invoiceService->getErrMsg()); 
    }        

    /**
     * 获取开票单位
     * @param string $keyword 搜索关键字
     * @return array 
     */
    public function actionGetInvoiceBusinessUnit($keyword = '') {
        $data = $this->_invoiceService->getInvoiceBusinessUnit($keyword);
        $this->exportJson($data, $this->_invoiceService->getErrCode(), $this->_invoiceService->getErrMsg());
    }

    /*发送邮件提醒*/
    /**
     * 过期未全部回款的发票发送提醒
     */
    public function actionInvoiceExpiredRemind(){
        $this->_invoiceService->invoiceExpiredRemind();
    }
    
    /**
     * 导出发票/收据 excel
     */
    public function actionExportInvoice () {
		$isMainInvoice = empty($this->getParam('is_main_invoice')) ? "-1" : $this->getParam('is_main_invoice');
		$invoiceStatus = empty($this->getParam('invoice_status')) ? "-1" : $this->getParam('invoice_status');
		$invoiceBeginDate = $this->getParam('invoice_begin_date');
		$invoiceEndDate = $this->getParam('invoice_end_date');
		$searchKey = $this->getParam('searchKey');
        $isReceipt = $this->getParam('is_receipt','get', 0);

        $data = $this->_invoiceService->exportInvoiceListExcel($isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey, $isReceipt);
        $this->exportJson($data, $this->_invoiceService->getErrCode(), $this->_invoiceService->getErrMsg());
    }

    /**
     * 导出未关联发票的回款明细
     */
    public function actionExportUnInvoicePayment()
    {
        $data = $this->_invoiceService->exportUnInvoicePayment();
        $this->exportJson($data, $this->_invoiceService->getErrCode(), $this->_invoiceService->getErrMsg());
    }

    /**
     * 导入发票 excel
     */
    public function actionImportInvoice() {
        if (!isset($_FILES['file'])) {
            $this->exportJson([], -1, "未上传文件");
        }
        if($_FILES["file"]["error"]>0){
            switch ($_FILES["file"]["error"])
            {
                case 1:
                    $error_msg = '上传文件大小超过php.ini中upload_max_filesize 选项限制的值';
                    break;
                case 2:
                    $error_msg = '上传文件大小超过 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
                    break;
                case 3:
                    $error_msg = '文件只有部分被上传';
                    break;
                case 4:
                    $error_msg = '没有文件被上传';
                    break;
                default:
                    $error_msg = '错误码为'.$_FILES["file"]["error"];
            }
            $this->exportJson([], -1, $error_msg);
        }
        $filePath = $_FILES['file']['tmp_name'];
        $invoiceService = \Yii::createObject(InvoiceService::className());
        $res = $this->_invoiceService->importInvoiceByExcel($filePath);
        $this->exportJson($res, $invoiceService->getErrCode(), $invoiceService->getErrMsg());
    }


}
